<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :modal-style="{ maxWidth: '520px' }"
    width="90%"
    @before-ok="save"
    @close="reset"
  >
    <a-from>
      <a-form-item label="微信openId" field="openId">
        <a-input v-model.trim="form.openId" placeholder="请输入微信openId" :max-length="50" show-word-limit />
      </a-form-item>
      <a-form-item label="昵称" field="nickename">
        <a-input v-model.trim="form.nickename" placeholder="请输入昵称" :max-length="30" show-word-limit />
      </a-form-item>
      <a-form-item label="头像" field="avatar">
        <!-- <a-upload :file-list="avatarList" accept="image/*" :show-file-list="false" list-type="picture-card"
          :show-upload-button="true" :on-before-upload="onBeforeUpload">
          <template #upload-button>
            <Avatar :src="avatarList[0].url" :name="form.avatarname" :size="80" trigger>
              <template #trigger-icon><icon-camera /></template>
            </Avatar>
          </template>
        </a-upload> -->
      </a-form-item>
    </a-from>
  </a-modal>
</template>

<script setup lang="ts">
import { addWechatUser, getWechatUser, updateWechatUser } from '@/apis/website/wechatUser';
import { GiForm, type Columns, type Options } from '@/components/GiForm';
import { useForm } from '@/hooks';
import { Message } from '@arco-design/web-vue';

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改微信用户' : '新增微信用户'))
const formRef = ref<InstanceType<typeof GiForm>>()


const options: Options = {
  form: {},
  btns: { hide: true }
}

const { form, resetForm } = useForm({
  // todo 待补充
})

const columns = computed<Columns<typeof form>>(() => [
  {
    label: '微信openId',
    field: 'openId',
    type: 'input',
    rules: [{ required: true, message: '请输入微信openId' }]
  },
  {
    label: '性别（0：未知；1：男；2：女）',
    field: 'gender',
    type: 'input',
    rules: [{ required: true, message: '请输入性别（0：未知；1：男；2：女）' }]
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const res = await getWechatUser(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateWechatUser(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addWechatUser(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
